package com.example.javamaday.offer;

public class GetOffer29 {

    public static void main(String[] args) {

    }

    private int[] result;
    private int index = 0;

    public int[] spiralOrder(int[][] matrix) {
        int tRow = 0;
        int tCol = 0;
        int dRow = matrix.length - 1;
        int dCol = matrix.length == 0 ? 0 : matrix[0].length - 1;
        result = new int[matrix.length * (matrix.length == 0 ? 0 : matrix[0].length)];
        if (result.length == 0) {
            return result;
        }
        while (tRow <= dRow && tCol <= dCol) {
            scanMatrix(matrix, tRow++, tCol++, dRow--, dCol--);
        }
        return result;
    }

    private void scanMatrix(int[][] matrix, int tRow, int tCol, int dRow, int dCol) {
        if (tRow == dRow && tCol == dCol) {
            result[index++] = matrix[tRow][tCol];
            return;
        }
        if (tRow == dRow && tCol != dCol) {
            for (int i = tCol; i <= dCol; i++) {
                result[index++] = matrix[tRow][i];
            }
            return;
        }
        if (tRow != dRow && tCol == dCol) {
            for (int i = tRow; i <= dRow; i++) {
                result[index++] = matrix[i][dCol];
            }
            return;
        }
        if (tRow != dRow && tCol != dCol) {
            for (int i = tCol; i < dCol; i++) {
                result[index++] = matrix[tRow][i];
            }
            for (int i = tRow; i < dRow; i++) {
                result[index++] = matrix[i][dCol];
            }
            for (int i = dCol; i > tCol; i--) {
                result[index++] = matrix[dRow][i];
            }
            for (int i = dRow; i > tRow; i--) {
                result[index++] = matrix[i][tCol];
            }
        }
    }

}
